package com.example.VolunteerBank.service.impl;

import com.example.VolunteerBank.mapper.UserMapper;
import com.example.VolunteerBank.pojo.User;
import com.example.VolunteerBank.service.UserService;
import com.example.VolunteerBank.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //根据名字查找用户
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    //添加用户
    @Override
    public void add(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.add(user);
    }

    //更新用户详细信息
    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    //更新用户头像
    @Override
    public void updateAvatar(String avatarUrl) {
        User user = new User();
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        user.setId(id);
        user.setUpdateTime(LocalDateTime.now());
        user.setUserPic(avatarUrl);
        userMapper.update(user);
    }

    //更新用户密码
    @Override
    public void updatePwd(String newPwd) {
        User user = new User();
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        user.setId(id);
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
        userMapper.update(user);
    }
}
